package com.srp.backend.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.srp.backend.entity.PdfParseResult;
import com.srp.backend.mapper.PdfParseResultMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class PdfProcessingService {

    @Autowired
    private PdfParseResultMapper pdfParseResultMapper;

    @Value("${app.python-exec}")
    private String pythonExec;

    @Value("${app.python-script}")
    private String pythonScriptRelative;


    /**
     * 解析 PDF 文件并保存结果到数据库
     * @param filePath 已上传 PDF 文件在服务器的路径
     * @param exportFormat 可选输出方式，默认为 “word”
     * @return Map<String,Object> JSON 格式解析结果
     */
    public Map<String, Object> processPdf(String filePath, String exportFormat) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 绝对路径
            String projectRoot = System.getProperty("user.dir");
            String pythonScriptPath = projectRoot + "/" + pythonScriptRelative;

            ProcessBuilder pb = new ProcessBuilder(pythonExec, pythonScriptPath, filePath, exportFormat);
            Process process = pb.start();

            // 异步读取 stdout
            StringBuilder outputBuilder = new StringBuilder();
            Thread stdoutThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        outputBuilder.append(line);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            // 异步读取 stderr
            Thread stderrThread = new Thread(() -> {
                try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.err.println(line); // 日志输出
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            stdoutThread.start();
            stderrThread.start();

            int exitCode = process.waitFor();
            stdoutThread.join();
            stderrThread.join();

            if (exitCode != 0) {
                throw new RuntimeException("Python 脚本执行失败，退出码：" + exitCode);
            }

            // 解析 Python 返回的 JSON
            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> pythonResult = mapper.readValue(outputBuilder.toString(), Map.class);

            result.put("status", "SUCCESS");
            result.put("json_paths", pythonResult.get("json_paths"));
            result.put("visual_paths", pythonResult.get("visual_paths"));
            result.put("output_dir", pythonResult.get("output_dir"));
            if (pythonResult.containsKey("word_path")) {
                result.put("word_path", pythonResult.get("word_path"));
                result.put("excel_path", null);
            }
            if (pythonResult.containsKey("excel_path")) {
                result.put("word_path", null);
                result.put("excel_path", pythonResult.get("excel_path"));
            }


        } catch (Exception e) {
            result.put("status", "FAILED");
            result.put("json_paths", null);
            result.put("visual_paths", null);
            result.put("output_dir", null);
            result.put("word_path", null);
            result.put("excel_path", null);
            result.put("error", e.getMessage());
        }

        // 保存解析结果到数据库
        PdfParseResult parseResult = new PdfParseResult();
        parseResult.setFilePath(filePath);
        parseResult.setStatus((String) result.get("status"));
        try {
            ObjectMapper mapper = new ObjectMapper();
            parseResult.setContent(mapper.writeValueAsString(result));
        } catch (Exception ignored) {}
        parseResult.setCreateTime(LocalDateTime.now());

        pdfParseResultMapper.insert(parseResult);

        return result;
    }
}
